package com.lcq.gulimall.authsever.web;

import com.lcq.common.exception.BizCodeEnum;
import com.lcq.common.utils.R;
import com.lcq.gulimall.authsever.feign.MemberFeign;
import com.lcq.gulimall.authsever.utils.AuthCodeUtils;
import com.lcq.gulimall.authsever.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class RegWebController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeign memberFeign;
    @RequestMapping("/auth/register")
    public String register(@Valid RegisterVo registerVo, BindingResult bindingResult,
                           RedirectAttributes redirectAttributes){
        /**
         * 参数校验
         */
        Map<String, String> errors = null;
        if(bindingResult.hasErrors()){
            errors = bindingResult.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        /**
         * 验证码比对
         */
        String code = AuthCodeUtils.getSaveCode(redisTemplate,registerVo.getPhone());
        if(!code.equals(registerVo.getAuthCode())){
            errors = new HashMap<>();
            errors.put("authCode","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        R result = memberFeign.register(registerVo);
        Integer resCode = (Integer) result.get("code");
        if(resCode != 0){
            errors = new HashMap<>();
            if (resCode.equals(BizCodeEnum.MEMBER_PHONE_EXIST_EXCEPTION.getCode())){
                errors.put("phone",(String) result.get("msg"));
            }else if (resCode.equals(BizCodeEnum.MEMBER_USERNAME_EXIST_EXCEPTION.getCode())){
                errors.put("userName",(String) result.get("msg"));
            }else {
                errors.put(resCode.toString(),(String) result.get("msg"));
            }
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
